package algo.ch0103;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * @author mougua
 */
public class Bag<E> implements Iterable<E> {
    private Node first;
    private int n;
    private class Node {
        E e;
        Node next;
        Node(E e, Node next){
            this.e = e;
            this.next = next;
        }
    }
    @Override
    public Iterator<E> iterator() {
        return new ListIterator();
    }

    void add(E e) {
        Node oldFirst = first;
        first = new Node(e, oldFirst);
        n++;
    }

    boolean isEmpty() {
        return first == null;
    }

    int size() {
        return n;
    }

    private class ListIterator implements Iterator<E>{
        private Node current = first;

        @Override
        public boolean hasNext() {
            return current != null;
        }

        @Override
        public E next() throws NoSuchElementException {
            if (current == null) {
                throw new NoSuchElementException();
            }
            E e = current.e;
            current = current.next;
            return e;
        }

        @Override
        public void remove() {

        }
    }

}
